package com.labManage.service.impl;

import com.labManage.dao.PermitionDao;
import com.labManage.entity.Permition;
import com.labManage.entity.User;
import com.labManage.service.PermitionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class PermitionServiceImpl implements PermitionService {
    @Autowired
    PermitionDao permitionDao;
    @Override
    public int deletePermitionInfo(Long permitionId) {
        int result = permitionDao.selectCountChildByPerimitionParentId(permitionId);
        if(0<result){
            return 1;
        }else {
            int deteteResult = permitionDao.deletePermitionInfoByPermitionId(permitionId);
            if(0<deteteResult){
                return 2;
            }else{
                return 0;
            }
        }
    }

    @Override
    public int addPermitionInfo(Permition permition) {
        permition.setCreateTime(new Date());
        permition.setModifyTime(new Date());
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User)subject.getPrincipal();
        permition.setCreatePerson(loginUser.getUsername());
        permition.setModifyPerson(loginUser.getUsername());
        if(null==permition.getId()){
            permition.setParentId(null);
        }else{
            permition.setParentId(Math.toIntExact(permition.getId()));
        }
        int result = permitionDao.insertPermitionInfo(permition);
        return result;
    }

    @Override
    public int modifyPermitionInfo(Permition permition) {
        permition.setCreateTime(new Date());
        permition.setModifyTime(new Date());
        Subject subject = SecurityUtils.getSubject();
        User loginUser = (User)subject.getPrincipal();
        permition.setCreatePerson(loginUser.getUsername());
        permition.setModifyPerson(loginUser.getUsername());
        int result = permitionDao.updatePermitionInfoById(permition);
        return result;
    }
}
